import json
import time
import uuid
from com.aes_util import AESUtil

class RequestEncryptor:
    @staticmethod
    def encrypt_request(data: dict, aes_key: str = None) -> str:
        """
        加密请求数据
        :param data: 要加密的请求数据字典
        :param aes_key: AES密钥
        :return: 加密后的请求数据
        """
        if aes_key is None:
            aes_key = str(uuid.uuid4()).replace('-', '')
        try:
            # 将数据转换为JSON字符串
            json_str = json.dumps(data, ensure_ascii=False)
            # 使用AES加密JSON数据
            encrypted_data = AESUtil.encrypt_str(json_str, aes_key)
            return encrypted_data
        except Exception as e:
            print(f"加密失败: {e}")
            raise e
            
    @staticmethod
    def encrypt(data: str, aes_key: str) -> str:
        """
        加密请求数据
        :param data: 要加密的数据字符串
        :param aes_key: AES密钥
        :return: 加密后的请求数据
        """
        try:
            # 使用AES加密数据
            encrypted_data = AESUtil.encrypt_str(data, aes_key)
            return encrypted_data
        except Exception as e:
            print(f"加密失败: {e}")
            raise e

def test_encryption():
    """测试加密功能"""
    # 测试数据
    test_data = {
        "orderId": "202501242001001",
        "amount": 100.00,
        "currency": "CNY",
        "description": "测试订单"
    }
    

    
    try:
        print("=== 开始加密测试 ===")
        print(f"原始数据: {json.dumps(test_data, ensure_ascii=False, indent=2)}")

        
        # 加密数据
        encrypted_data = RequestEncryptor.encrypt_request(test_data)
        print(f"\n加密后的数据: {encrypted_data}")
        print(f"加密数据长度: {len(encrypted_data)}")
        
        print("=== 加密测试完成 ===")
        
        return encrypted_data
        
    except Exception as e:
        print(f"测试失败: {e}")
        raise

if __name__ == "__main__":
    test_encryption()
